import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';

/// AI对话交互界面组件
/// 支持需求分析、文档生成、智能建议等AI辅助功能
class AiChatWidget extends ConsumerStatefulWidget {
  final String? initialMessage;
  final Function(String)? onMessageSent;
  final Function(String)? onResponseReceived;

  const AiChatWidget({
    super.key,
    this.initialMessage,
    this.onMessageSent,
    this.onResponseReceived,
  });

  @override
  ConsumerState<AiChatWidget> createState() => _AiChatWidgetState();
}

class _AiChatWidgetState extends ConsumerState<AiChatWidget> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  final List<ChatMessage> _messages = [];
  bool _isLoading = false;

  @override
  void initState() {
    super.initState();
    if (widget.initialMessage != null) {
      _messageController.text = widget.initialMessage!;
    }
    _initializeChat();
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  /// 初始化聊天
  void _initializeChat() {
    _messages.add(ChatMessage(
      content: '您好！我是FlowPlan智能助手，可以帮助您：\\n\\n'
          '📋 分析需求文档\\n'
          '📝 生成功能规格\\n'
          '🧪 创建测试用例\\n'
          '💡 提供智能建议\\n\\n'
          '请描述您需要帮助的内容，我会尽力为您提供专业的建议。',
      isUser: false,
      timestamp: DateTime.now(),
      messageType: ChatMessageType.greeting,
    ));
  }

  /// 发送消息
  Future<void> _sendMessage() async {
    final message = _messageController.text.trim();
    if (message.isEmpty || _isLoading) return;

    // 添加用户消息
    setState(() {
      _messages.add(ChatMessage(
        content: message,
        isUser: true,
        timestamp: DateTime.now(),
        messageType: ChatMessageType.text,
      ));
      _isLoading = true;
    });

    _messageController.clear();
    _scrollToBottom();

    // 通知父组件
    if (widget.onMessageSent != null) {
      widget.onMessageSent!(message);
    }

    try {
      // 模拟AI响应
      await Future.delayed(const Duration(seconds: 2));

      final response = await _getAiResponse(message);

      setState(() {
        _messages.add(ChatMessage(
          content: response.content,
          isUser: false,
          timestamp: DateTime.now(),
          messageType: response.type,
          suggestions: response.suggestions,
          attachments: response.attachments,
        ));
        _isLoading = false;
      });

      // 通知父组件
      if (widget.onResponseReceived != null) {
        widget.onResponseReceived!(response.content);
      }
    } catch (e) {
      setState(() {
        _messages.add(ChatMessage(
          content: '抱歉，AI服务暂时不可用，请稍后重试。错误信息：${e.toString()}',
          isUser: false,
          timestamp: DateTime.now(),
          messageType: ChatMessageType.error,
        ));
        _isLoading = false;
      });
    }

    _scrollToBottom();
  }

  /// 获取AI响应
  Future<AiResponse> _getAiResponse(String message) async {
    // TODO: 调用实际的AI API
    // 这里模拟不同类型的响应

    if (message.contains('需求') || message.contains('分析')) {
      return AiResponse(
        content: '基于您的需求描述，我分析如下：\\n\\n'
            '🎯 **核心功能点**：\\n'
            '• 用户管理系统\\n'
            '• 权限控制机制\\n'
            '• 数据存储方案\\n\\n'
            '📊 **技术建议**：\\n'
            '• 建议使用Spring Security进行权限管理\\n'
            '• 数据库建议使用PostgreSQL\\n'
            '• 前端建议使用React或Vue.js\\n\\n'
            '⚠️ **风险提醒**：\\n'
            '• 需要考虑数据安全性\\n'
            '• 注意系统性能优化',
        type: ChatMessageType.analysis,
        suggestions: [
          '生成详细的功能规格文档',
          '创建对应的测试用例',
          '制定开发排期计划',
        ],
      );
    } else if (message.contains('文档') || message.contains('生成')) {
      return AiResponse(
        content: '我为您生成了相关文档内容：\\n\\n'
            '# 功能规格说明书\\n\\n'
            '## 1. 功能概述\\n'
            '本功能旨在实现用户的核心需求，提供完整的业务流程支持。\\n\\n'
            '## 2. 功能详细说明\\n'
            '### 2.1 用户界面\\n'
            '- 提供直观的操作界面\\n'
            '- 支持响应式设计\\n'
            '- 符合用户体验标准\\n\\n'
            '### 2.2 业务逻辑\\n'
            '- 数据验证机制\\n'
            '- 错误处理流程\\n'
            '- 状态管理方案\\n\\n'
            '## 3. 技术实现\\n'
            '- API接口设计\\n'
            '- 数据库设计\\n'
            '- 安全措施',
        type: ChatMessageType.document,
        attachments: [
          ChatAttachment(
            name: '功能规格文档.md',
            type: 'document',
            size: '2.5KB',
          ),
        ],
      );
    } else if (message.contains('测试') || message.contains('用例')) {
      return AiResponse(
        content: '已为您生成测试用例：\\n\\n'
            '## 测试用例设计\\n\\n'
            '### TC001 - 用户登录功能测试\\n'
            '**测试目标**：验证用户登录功能正常工作\\n'
            '**前置条件**：用户账号已注册并激活\\n'
            '**测试步骤**：\\n'
            '1. 打开登录页面\\n'
            '2. 输入正确的用户名和密码\\n'
            '3. 点击登录按钮\\n'
            '**预期结果**：用户成功登录，跳转到首页\\n\\n'
            '### TC002 - 数据验证测试\\n'
            '**测试目标**：验证输入数据验证机制\\n'
            '**测试步骤**：\\n'
            '1. 输入无效数据\\n'
            '2. 提交表单\\n'
            '**预期结果**：显示相应的错误提示',
        type: ChatMessageType.testCase,
        suggestions: [
          '生成更多测试场景',
          '创建自动化测试脚本',
          '制定测试执行计划',
        ],
      );
    } else {
      return AiResponse(
        content: '感谢您的问题！基于您的描述，我为您提供以下建议：\\n\\n'
            '💡 **智能建议**：\\n'
            '• 建议先明确具体的功能需求\\n'
            '• 可以提供更详细的背景信息\\n'
            '• 如需具体的技术方案，请告知技术栈偏好\\n\\n'
            '🔧 **可以帮助您的功能**：\\n'
            '• 需求分析和功能设计\\n'
            '• 技术方案制定\\n'
            '• 文档生成和规范制定\\n'
            '• 测试用例设计',
        type: ChatMessageType.suggestion,
        suggestions: [
          '我需要分析具体需求',
          '帮我生成技术文档',
          '为我设计测试用例',
          '提供开发建议',
        ],
      );
    }
  }

  /// 滚动到底部
  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  /// 选择建议
  void _selectSuggestion(String suggestion) {
    _messageController.text = suggestion;
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        // 聊天消息列表
        Expanded(
          child: Container(
            decoration: BoxDecoration(
              color: Colors.grey.shade50,
              borderRadius: const BorderRadius.only(
                topLeft: Radius.circular(12),
                topRight: Radius.circular(12),
              ),
            ),
            child: ListView.builder(
              controller: _scrollController,
              padding: const EdgeInsets.all(16),
              itemCount: _messages.length + (_isLoading ? 1 : 0),
              itemBuilder: (context, index) {
                if (index == _messages.length && _isLoading) {
                  return _buildLoadingMessage();
                }
                return _buildMessageBubble(_messages[index]);
              },
            ),
          ),
        ),

        // 输入区域
        _buildInputArea(),
      ],
    );
  }

  /// 构建消息气泡
  Widget _buildMessageBubble(ChatMessage message) {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          if (!message.isUser) ...[
            // AI头像
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                color: Colors.blue.shade100,
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.smart_toy,
                size: 20,
                color: Colors.blue,
              ),
            ),
            const SizedBox(width: 12),
          ],
          Expanded(
            child: Column(
              crossAxisAlignment: message.isUser
                  ? CrossAxisAlignment.end
                  : CrossAxisAlignment.start,
              children: [
                // 消息内容
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: message.isUser ? Colors.blue.shade500 : Colors.white,
                    borderRadius: BorderRadius.circular(12),
                    boxShadow: [
                      BoxShadow(
                        color: Colors.black.withValues(alpha: 0.05),
                        blurRadius: 4,
                        offset: const Offset(0, 2),
                      ),
                    ],
                  ),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // 消息类型标签
                      if (!message.isUser &&
                          message.messageType != ChatMessageType.text)
                        Container(
                          margin: const EdgeInsets.only(bottom: 8),
                          padding: const EdgeInsets.symmetric(
                            horizontal: 8,
                            vertical: 4,
                          ),
                          decoration: BoxDecoration(
                            color: _getMessageTypeColor(message.messageType)
                                .withValues(alpha: 0.1),
                            borderRadius: BorderRadius.circular(12),
                          ),
                          child: Row(
                            mainAxisSize: MainAxisSize.min,
                            children: [
                              Icon(
                                _getMessageTypeIcon(message.messageType),
                                size: 12,
                                color:
                                    _getMessageTypeColor(message.messageType),
                              ),
                              const SizedBox(width: 4),
                              Text(
                                _getMessageTypeText(message.messageType),
                                style: TextStyle(
                                  fontSize: 10,
                                  color:
                                      _getMessageTypeColor(message.messageType),
                                  fontWeight: FontWeight.w500,
                                ),
                              ),
                            ],
                          ),
                        ),

                      // 消息文本
                      SelectableText(
                        message.content,
                        style: TextStyle(
                          color: message.isUser ? Colors.white : Colors.black87,
                          fontSize: 14,
                          height: 1.4,
                        ),
                      ),

                      // 附件
                      if (message.attachments?.isNotEmpty == true)
                        ...message.attachments!
                            .map((attachment) => _buildAttachment(attachment)),
                    ],
                  ),
                ),

                // 建议选项
                if (message.suggestions?.isNotEmpty == true) ...[
                  const SizedBox(height: 8),
                  Wrap(
                    spacing: 8,
                    runSpacing: 4,
                    children: message.suggestions!
                        .map(
                          (suggestion) => GestureDetector(
                            onTap: () => _selectSuggestion(suggestion),
                            child: Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 12,
                                vertical: 6,
                              ),
                              decoration: BoxDecoration(
                                color: Colors.blue.shade50,
                                borderRadius: BorderRadius.circular(16),
                                border: Border.all(
                                  color: Colors.blue.shade200,
                                ),
                              ),
                              child: SelectableText(
                                suggestion,
                                style: TextStyle(
                                  color: Colors.blue.shade700,
                                  fontSize: 12,
                                ),
                              ),
                            ),
                          ),
                        )
                        .toList(),
                  ),
                ],

                // 时间戳
                const SizedBox(height: 4),
                SelectableText(
                  _formatTime(message.timestamp),
                  style: TextStyle(
                    color: Colors.grey.shade500,
                    fontSize: 10,
                  ),
                ),
              ],
            ),
          ),
          if (message.isUser) ...[
            const SizedBox(width: 12),
            // 用户头像
            Container(
              width: 32,
              height: 32,
              decoration: BoxDecoration(
                color: Colors.green.shade100,
                shape: BoxShape.circle,
              ),
              child: const Icon(
                Icons.person,
                size: 20,
                color: Colors.green,
              ),
            ),
          ],
        ],
      ),
    );
  }

  /// 构建加载消息
  Widget _buildLoadingMessage() {
    return Container(
      margin: const EdgeInsets.only(bottom: 16),
      child: Row(
        children: [
          Container(
            width: 32,
            height: 32,
            decoration: BoxDecoration(
              color: Colors.blue.shade100,
              shape: BoxShape.circle,
            ),
            child: const Icon(
              Icons.smart_toy,
              size: 20,
              color: Colors.blue,
            ),
          ),
          const SizedBox(width: 12),
          Container(
            padding: const EdgeInsets.all(12),
            decoration: BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.circular(12),
              boxShadow: [
                BoxShadow(
                  color: Colors.black.withValues(alpha: 0.05),
                  blurRadius: 4,
                  offset: const Offset(0, 2),
                ),
              ],
            ),
            child: Row(
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 16,
                  height: 16,
                  child: CircularProgressIndicator(
                    strokeWidth: 2,
                    valueColor:
                        AlwaysStoppedAnimation<Color>(Colors.blue.shade300),
                  ),
                ),
                const SizedBox(width: 8),
                SelectableText(
                  'AI正在思考中...',
                  style: TextStyle(
                    color: Colors.grey.shade600,
                    fontSize: 14,
                  ),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }

  /// 构建附件
  Widget _buildAttachment(ChatAttachment attachment) {
    return Container(
      margin: const EdgeInsets.only(top: 8),
      padding: const EdgeInsets.all(8),
      decoration: BoxDecoration(
        color: Colors.grey.shade100,
        borderRadius: BorderRadius.circular(8),
      ),
      child: Row(
        children: [
          Icon(
            _getAttachmentIcon(attachment.type),
            size: 16,
            color: Colors.grey.shade600,
          ),
          const SizedBox(width: 8),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  attachment.name,
                  style: const TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Text(
                  attachment.size,
                  style: TextStyle(
                    fontSize: 10,
                    color: Colors.grey.shade600,
                  ),
                ),
              ],
            ),
          ),
          IconButton(
            onPressed: () {
              // TODO: 实现下载功能
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('下载功能开发中...')),
              );
            },
            icon: const Icon(Icons.download, size: 16),
            padding: EdgeInsets.zero,
            constraints: const BoxConstraints(
              minWidth: 24,
              minHeight: 24,
            ),
          ),
        ],
      ),
    );
  }

  /// 构建输入区域
  Widget _buildInputArea() {
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: const BorderRadius.only(
          bottomLeft: Radius.circular(12),
          bottomRight: Radius.circular(12),
        ),
        boxShadow: [
          BoxShadow(
            color: Colors.black.withValues(alpha: 0.05),
            blurRadius: 4,
            offset: const Offset(0, -2),
          ),
        ],
      ),
      child: Row(
        children: [
          // 快捷功能按钮
          PopupMenuButton<String>(
            onSelected: (value) {
              switch (value) {
                case 'analyze':
                  _messageController.text = '请帮我分析这个需求的技术实现方案';
                  break;
                case 'document':
                  _messageController.text = '请为这个功能生成详细的技术文档';
                  break;
                case 'test':
                  _messageController.text = '请为这个功能设计完整的测试用例';
                  break;
              }
            },
            icon: Icon(Icons.add_circle_outline, color: Colors.grey.shade600),
            itemBuilder: (context) => [
              const PopupMenuItem(
                value: 'analyze',
                child: Row(
                  children: [
                    Icon(Icons.analytics, size: 16),
                    SizedBox(width: 8),
                    SelectableText('需求分析'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'document',
                child: Row(
                  children: [
                    Icon(Icons.description, size: 16),
                    SizedBox(width: 8),
                    SelectableText('生成文档'),
                  ],
                ),
              ),
              const PopupMenuItem(
                value: 'test',
                child: Row(
                  children: [
                    Icon(Icons.bug_report, size: 16),
                    SizedBox(width: 8),
                    SelectableText('测试用例'),
                  ],
                ),
              ),
            ],
          ),

          const SizedBox(width: 8),

          // 输入框
          Expanded(
            child: TextField(
              controller: _messageController,
              decoration: InputDecoration(
                hintText: '输入您的问题或需求...',
                border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(24),
                  borderSide: BorderSide.none,
                ),
                filled: true,
                fillColor: Colors.grey.shade100,
                contentPadding: const EdgeInsets.symmetric(
                  horizontal: 16,
                  vertical: 12,
                ),
              ),
              maxLines: null,
              textInputAction: TextInputAction.send,
              onSubmitted: (_) => _sendMessage(),
            ),
          ),

          const SizedBox(width: 8),

          // 发送按钮
          GestureDetector(
            onTap: _sendMessage,
            child: Container(
              width: 40,
              height: 40,
              decoration: BoxDecoration(
                color: _messageController.text.trim().isEmpty || _isLoading
                    ? Colors.grey.shade300
                    : Colors.blue.shade500,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.send,
                size: 20,
                color: _messageController.text.trim().isEmpty || _isLoading
                    ? Colors.grey.shade600
                    : Colors.white,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 获取消息类型颜色
  Color _getMessageTypeColor(ChatMessageType type) {
    switch (type) {
      case ChatMessageType.analysis:
        return Colors.blue;
      case ChatMessageType.document:
        return Colors.green;
      case ChatMessageType.testCase:
        return Colors.orange;
      case ChatMessageType.suggestion:
        return Colors.purple;
      case ChatMessageType.error:
        return Colors.red;
      default:
        return Colors.grey;
    }
  }

  /// 获取消息类型图标
  IconData _getMessageTypeIcon(ChatMessageType type) {
    switch (type) {
      case ChatMessageType.analysis:
        return Icons.analytics;
      case ChatMessageType.document:
        return Icons.description;
      case ChatMessageType.testCase:
        return Icons.bug_report;
      case ChatMessageType.suggestion:
        return Icons.lightbulb;
      case ChatMessageType.error:
        return Icons.error;
      default:
        return Icons.chat;
    }
  }

  /// 获取消息类型文本
  String _getMessageTypeText(ChatMessageType type) {
    switch (type) {
      case ChatMessageType.analysis:
        return '需求分析';
      case ChatMessageType.document:
        return '文档生成';
      case ChatMessageType.testCase:
        return '测试用例';
      case ChatMessageType.suggestion:
        return '智能建议';
      case ChatMessageType.error:
        return '错误信息';
      case ChatMessageType.greeting:
        return '欢迎消息';
      default:
        return '普通消息';
    }
  }

  /// 获取附件图标
  IconData _getAttachmentIcon(String type) {
    switch (type) {
      case 'document':
        return Icons.description;
      case 'image':
        return Icons.image;
      case 'code':
        return Icons.code;
      default:
        return Icons.attach_file;
    }
  }

  /// 格式化时间
  String _formatTime(DateTime time) {
    final now = DateTime.now();
    final difference = now.difference(time);

    if (difference.inMinutes < 1) {
      return '刚刚';
    } else if (difference.inHours < 1) {
      return '${difference.inMinutes}分钟前';
    } else if (difference.inDays < 1) {
      return '${difference.inHours}小时前';
    } else {
      return '${time.month}/${time.day} ${time.hour}:${time.minute.toString().padLeft(2, '0')}';
    }
  }
}

/// 聊天消息数据模型
class ChatMessage {
  final String content;
  final bool isUser;
  final DateTime timestamp;
  final ChatMessageType messageType;
  final List<String>? suggestions;
  final List<ChatAttachment>? attachments;

  const ChatMessage({
    required this.content,
    required this.isUser,
    required this.timestamp,
    this.messageType = ChatMessageType.text,
    this.suggestions,
    this.attachments,
  });
}

/// 聊天消息类型枚举
enum ChatMessageType {
  text,
  greeting,
  analysis,
  document,
  testCase,
  suggestion,
  error,
}

/// AI响应数据模型
class AiResponse {
  final String content;
  final ChatMessageType type;
  final List<String>? suggestions;
  final List<ChatAttachment>? attachments;

  const AiResponse({
    required this.content,
    this.type = ChatMessageType.text,
    this.suggestions,
    this.attachments,
  });
}

/// 聊天附件数据模型
class ChatAttachment {
  final String name;
  final String type;
  final String size;

  const ChatAttachment({
    required this.name,
    required this.type,
    required this.size,
  });
}
